package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.service.impl.ShopServiceImpl.CACHE_REBUILD_EXECUTOR;

/**
 * @author 寒士obj
 * @date 2025/07/04 22:39
 **/
@Slf4j
@Component
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置带有过期时间的缓存
     *
     * @param key
     * @param value
     * @param time
     */
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 设置逻辑过期缓存
     *
     * @param key
     * @param value
     * @param time
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        // 设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
        // 写入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <T, ID> T queryWithLogicalExpire(String keyPrefix, ID id, Class<T> type, Function<ID, T> dbFallback, Long time, TimeUnit unit) {
        // 1. 获取缓存数据
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if (json == null) {
            // 3. 不存在，返回null
            return null;
        }
        // 4. 命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        T data = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 4.1 未过期，返回数据
            return data;
        }
        // 4.2 已过期，缓存重建
        String lockKey = "lock:" + key;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 5.1 获取锁成功，再次检查是否过期
            String json1 = stringRedisTemplate.opsForValue().get(key);
            RedisData redisData1 = JSONUtil.toBean(json1, RedisData.class);
            LocalDateTime expireTime1 = redisData1.getExpireTime();
            T data1 = JSONUtil.toBean((JSONObject) redisData1.getData(), type);
            if (expireTime1.isAfter(LocalDateTime.now())) {
                // 5.2 未过期，返回数据
                return data1;
            }
            // 5.3 已过期，缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                // 缓存重建
                try {
                    // 1. 重建缓存
                    T t1 = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, t1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 2. 释放锁
                    unLock(lockKey);
                }
            });
        }
        // 5.3 获取锁失败，返回数据
        return data;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 封装缓存穿透
     */
    public <T, ID> T queryWithPassThrough(String keyPrefix, ID id, Class<T> type, Function<ID, T> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            // 1. 存在，直接返回
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            // 2. 命中，返回错误
            return null;
        }

        // 3. 不存在，查询数据库
        T t = dbFallback.apply(id);
        if (t == null) {
            // 4. 数据库不存在，返回错误
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 5. 存在，写入缓存并设置30分钟有效期
        this.set(key, t, time, unit);

        // 6. 存在，返回
        return t;
    }

}
